// src/pages/Jian.jsx
import React, { useEffect, useCallback } from 'react';
import { motion } from 'framer-motion';
import { fadeIn } from '../styles/animations';
import VideoPlayer from '../components/VideoPlayer';
import PointsCircle from '../components/PointsCircle';
import WebSocketStatus from '../websocket/WebSocketStatus';
import usePlayVideoStore from '../store/playVideoStore';
import usePointsStore from '../store/pointsStore';
import { checkUserPermission } from '../utils/storage';
import { useWebSocket, MessageType } from '../websocket';

const Jian = () => {
  const hasPermission = checkUserPermission();

  // Video Store - Subscribe to the playlist directly
  const { 
    playlist,
    getCurrentVideo, 
    initPlaylist, 
    playPrevious, 
    playNext, 
    isFirstVideo, 
    isLastVideo, 
    isLoading, 
    resetState: resetVideoState
  } = usePlayVideoStore();
  
  // Points Store - extract all needed state and actions
  const {
    totalPoints,
    sessionPoints,
    canEarnPoints,
    nextAvailability,
    isInitialized: isPointsCheckComplete,
    isTimerActive,
    checkEligibility,
    accumulatePoints,
    setTimerActive,
    reset: resetPointsState,
  } = usePointsStore();

  // WebSocket Hook - 自动连接，监听消息
  const {
    status: wsStatus,
    isConnected: wsConnected,
    lastMessage: wsLastMessage,
    error: wsError,
    sendMessage: wsSendMessage,
    registerHandler: wsRegisterHandler,
    connect: wsConnect,
    disconnect: wsDisconnect
  } = useWebSocket({
    autoConnect: true,
    onMessage: (message) => {
      console.log('Jian页面收到WebSocket消息:', message);
      // 处理特定消息类型
      if (message.type === MessageType.NOTIFICATION) {
        // 显示通知消息
        console.log('收到通知:', message.data);
      }
    },
    onStatusChange: (status) => {
      console.log('WebSocket状态变化:', status);
    }
  });

  // 页面离开时清理资源
  useEffect(() => {
    return () => {
      // 页面离开时断开WebSocket连接
      wsDisconnect();
      resetVideoState();
      resetPointsState();
    };
  }, [wsDisconnect, resetVideoState, resetPointsState]);

  // Derive state within the component for reactive updates
  const isPlaylistActuallyEmpty = playlist.length === 0;

  // 修正 isEmpty 逻辑，放到解构之后
  const isEmpty = isPointsCheckComplete && !isLoading && isPlaylistActuallyEmpty;

  const currentVideo = getCurrentVideo();

  // 注册自定义消息处理器
  useEffect(() => {
    // 注册积分更新消息处理器
    wsRegisterHandler(MessageType.POINTS_UPDATE, (message) => {
      console.log('收到积分更新:', message.data);
      // 这里可以触发积分状态的重新检查
      checkEligibility();
    });

    // 注册视频更新消息处理器
    wsRegisterHandler(MessageType.VIDEO_UPDATE, (message) => {
      console.log('收到视频更新:', message.data);
      // 重新加载播放列表
      initPlaylist();
    });
  }, [wsRegisterHandler, checkEligibility, initPlaylist]);

  // Step 1: Check permission and then check points eligibility
  useEffect(() => {
    if (hasPermission) {
      checkEligibility();
    }
  }, [hasPermission, checkEligibility]);

  // Step 2: Once points check is complete, load the initial playlist
  useEffect(() => {
    // Now this effect correctly depends on reactive values
    if (isPointsCheckComplete && isPlaylistActuallyEmpty) {
      initPlaylist();
    }
  }, [isPointsCheckComplete, isPlaylistActuallyEmpty, initPlaylist]);

  // Memoized callbacks to prevent infinite re-render loops in VideoPlayer
  const handlePlay = useCallback(() => setTimerActive(true), [setTimerActive]);
  const handlePauseOrEnd = useCallback(() => setTimerActive(false), [setTimerActive]);

  // Memoized callback for the points circle timer to prevent resetting the interval
  const handleCycleComplete = useCallback(() => {
    const vid = usePlayVideoStore.getState().getCurrentVideo();
    if (vid?.url) {
      accumulatePoints(vid.url);
    }
  }, [accumulatePoints]);

  return (
    <motion.div 
      className="h-[calc(100vh-0.4rem)] bg-black relative"
      initial="hidden"
      animate="visible"
      exit="exit"
      variants={fadeIn}
    >
      {hasPermission ? (
        <>
          {/* 视频播放器 - 占据整个屏幕 */}
          <VideoPlayer 
            currentVideo={currentVideo}
            onSwipeUp={playPrevious}
            onSwipeDown={playNext}
            isFirstVideo={isFirstVideo()}
            isLastVideo={isLastVideo()}
            isLoading={isLoading}
            isEmpty={isEmpty}
            onPlay={handlePlay}
            onPause={handlePauseOrEnd}
            onEnded={handlePauseOrEnd}
          />
          
          {/* 积分圆圈 - 绝对定位在右上角，确保在视频播放器之上 */}
          {isPointsCheckComplete && (
            <div 
              className="absolute top-[0.4rem] right-[0.4rem] z-[9999] pointer-events-auto mobile-safe-area" 
              style={{ zIndex: 9999 }}
            >
              <PointsCircle
                totalPoints={totalPoints}
                sessionPoints={sessionPoints}
                onCycleComplete={handleCycleComplete}
                isTimerActive={isTimerActive}
                canEarnPoints={canEarnPoints}
                nextAvailability={nextAvailability}
              />
            </div>
          )}
          {/* WebSocket状态指示器 - 左下角显示 */}
          {/*<WebSocketStatus */}
          {/*  position="bottom-left"*/}
          {/*  showDetails={false}*/}
          {/*  showControls={true}*/}
          {/*  className="bg-black/80 backdrop-blur-sm border-gray-600"*/}
          {/*/>*/}
        </>
      ) : (
        <div className="flex items-center justify-center h-full">
          <div className="text-center text-white p-[0.6rem] bg-black/50 rounded-[0.2rem]">
            <h2 className="text-[0.4rem] font-bold mb-[0.2rem]">会员专享</h2>
            <p className="text-gray-300 text-[0.32rem]">您需要成为会员才能使用此功能</p>
            <p className="text-[0.28rem] text-gray-400 mt-[0.2rem]">开通会员即可解锁全部内容</p>
          </div>
        </div>
      )}
    </motion.div>
  );
};

export default Jian;
